<template>
  <div>
     <!-- 面包屑导航区域 -->
      <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片区域 -->
      <el-card>
          <!-- 添加角色按钮区域 -->
          <el-row>
              <el-col><el-button type="primary" @click="addRoleDialogVisible =true">添加角色</el-button></el-col>
          </el-row>
          <!-- 角色列表区域 -->
          <el-table :data="rolesList" border stripe>
              <!-- 展开列 -->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-row :class="[ 'bdbottom',i1 === '0' ? 'bdtop' :'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                    <!-- 渲染一级权限 -->
                    <el-col :span="5"><el-tag  closable @close="removeRightById(scope.row,item3.id)">{{item1.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                    <!-- 渲染二级和三级权限 -->
                    <el-col :span="19">
                      <el-row :class="[ 'bdtop',i2 === '0' ? 'bdbottom' :'','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                        <el-col :span="6"><el-tag type="success"  closable @close="removeRightById(scope.row,item3.id)">{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                        <el-col :span="18">
                            <el-col>
                              <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}<i class="el-icon-caret-right"></i></el-tag>
                            </el-col>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                {{scope.row}}
                </template>
              </el-table-column>
              <!-- 索引列 -->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="角色名称" prop="roleName"></el-table-column>
              <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
              <el-table-column label="操作" width="300px" >
                <template slot-scope= "scope" >
                <!-- 修改按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showRoleEditDialog(scope.row.id)">编辑</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
                <!-- 分配角色按钮 -->
                <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </el-tooltip>
                </template>
               </el-table-column>
          </el-table>

          <!-- 添加角色对话框 -->
            <el-dialog
            title="提示"
            :visible.sync="addRoleDialogVisible"
            width="50%"
            @closed="addRoleDialogClosed">
            <!-- 内容主体部分 -->
            <el-form :model="addRoleForm" :rules="addFormRules" ref="addRoleFormRef" label-width="70px"  >
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addRoleForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRoleForm.roleDesc"></el-input>
              </el-form-item>
              
            </el-form>
           

            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="addRoleDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
            </el-dialog>
            <!-- 编辑用户对话框 -->
            <el-dialog
              title="提示"
              :visible.sync="editRoleDialogVisible"
              width="50%"
              @closed="editRoleDialogClosed">
            <el-form :model="editRoleForm" :rules="editFormRules" ref="editRoleFormRef" label-width="170px" >
                  <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                  </el-form-item>
                  <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                  </el-form-item>
            </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="editRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoleInfo">确 定</el-button>
              </span>
            </el-dialog>
            <!-- 分配角色权限对话框 -->
            <el-dialog
                title="分配权限"
                :visible.sync="setRightDialogVisible"
                width="30%"
                @closed="setRightDialogClosed">
                <!-- // 树形控件 -->
                <el-tree :data="rightsList"
                 :props="treeProps" 
                 node-key="id" 
                 default-expand-all 
                 show-checkbox 
                 :default-checked-keys="defKeys"
                 ref="treeRef"></el-tree>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="setRightDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="allotRights">确 定</el-button>
                </span>
            </el-dialog>

      </el-card>
  </div>
</template>

<script>
import {rolesFormRulesMixin} from '../../common/mixin.js'

export default {
name: 'Roles',
mixins:[rolesFormRulesMixin],
data(){
    return{
        rolesList:[],
        addRoleForm:{
            roleName:'',
            roleDesc:''
        },
        editRoleForm:{

        },
        addRoleDialogVisible : false,
        editRoleDialogVisible :false,
        setRightDialogVisible : false,
        rightsList:[],
        // 树形控件的属性绑定对象
        treeProps:{
          label:'authName',
          children:'children'
        },
        defKeys:[

        ],
        // 当前分配权限角色ID
        roleId:''

        

    }
},
created(){
    this.getRolesList()
},
methods:{
    async getRolesList(){
        const {data:res} = await this.$http.get('roles')
        console.log(res);
        if(res.meta.status !=200){
            return this.$message.error(res.meta.msg)
        }
        this.rolesList =res.data
        this.$message.success(res.meta.msg) 
        console.log(this.rolesList);
    },
    addRole(){
        this.$refs.addRoleFormRef.validate(async valid=>{
            if(!valid) return
                const {data:res} =await this.$http.post('roles',this.addRoleForm)
                if(res.meta.status !==201) return this.$message.error(res.meta.msg)
                this.$message.success(res.meta.msg)
                this.addRoleDialogVisible = false
                this.getRolesList()

        })

        
    },
    addRoleDialogClosed(){
        this.$refs.addRoleFormRef.resetFields()
    },
     editRoleDialogClosed(){
        this.$refs.editRoleFormRef.resetFields()
    },
    //展示编辑对话框
    async showRoleEditDialog(id){
        const {data:res}= await this.$http.get('roles/'+ id)
        if(res.meta.status !==200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editRoleForm =res.data
        this.editRoleDialogVisible = true
    },
    //编辑角色并提交
  editRoleInfo(){
    this.$refs.editRoleFormRef.validate(async valid =>{
      // console.log(valid);
      if(!valid) return
      const {data:res} = await this.$http.put(`roles/${this.editRoleForm.roleId}`  ,
      {roleName:this.editRoleForm.roleName,
      roleDesc:this.editRoleForm.roleDesc,})
      if(res.meta.status !==200) return this.$message.error(res.meta.msg) 
     //关闭对话框
      this.editRoleDialogVisible =false 
      //  刷新数据列表
      this.getRolesList()
      // 提示修改成功
      this.$message.success(res.meta.msg)
        
    })
 },
    //删除角色
 async removeRoleById(id){
     const RoleconfirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
    if(RoleconfirmResult !== 'confirm'){
      return this.$message.info('已取消删除')
    }
     const {data:res} = await this.$http.delete('roles/' + id)

        if(res.meta.status !==200) {
          return this.$message.error('失败')
        }
        this.$message.success('成功')
        this.getRolesList()
 },
 async removeRightById(role,rightId){
   const comfirmResult=  await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(comfirmResult !== 'confirm'){
          return this.$message.error('取消删除')
        }
        
        const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if(res.meta.status !==200) {
          return this.$message.error('失败')
        }
        this.$message.success('成功')
        role.children =res.data

 },
 //显示分配角色对话框
 async showSetRightDialog(role){
   this.roleId = role.id
   const{data:res} = await this.$http.get('rights/tree')
   if(res.meta.status !==200){
     return this.$message.error(res.meta.msg)
   } 
   this.$message.success(res.meta.msg)
    this.rightsList =res.data
    console.log(this.rightsList);
    this.setRightDialogVisible = true
    this.getLeafKeys(role,this.defKeys)
 },
 //封装一个递归函数，然后点击分配权限在调用
//  通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys中
  getLeafKeys(node,arr){
    if(!node.children){
      return arr.push(node.id)
    }
    // 如果不是三级权限，则循环所有数组，每循环一项拿到子节点，
    // 再根据子节点item继续调用递归函数
    node.children.forEach(item =>
    this.getLeafKeys(item,arr))
  },
  setRightDialogClosed(){
    this.defKeys = []
  },
  async allotRights(){
    const keys =[
      ...this.$refs.treeRef.getCheckedKeys(),
      ...this.$refs.treeRef.getHalfCheckedKeys()
    ]
    console.log(keys);
    const idStr = keys.join(',')
    const{data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
    if(res.meta.status !==200){
      return this.$message.error(res.meta.msg)
    }
    this.$message.success(res.meta.msg)
    this.getRolesList()
    this.setRightDialogVisible =false
  }


}
}
</script>

<style  lang="less"scoped>

.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>